<template>
  <div class="category">
    <el-form :data="form" :label-width="formLabelWidth">
      <el-form-item label="类别名称：">
        <el-input v-model="form.name" placeholder="请输入类别名称"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="goBack">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import categoryApi from '@/api/category'
const defaultForm = {
  name: '',
  status: null
}
export default {
  data() {
    return {
      formLabelWidth: 100 + 'px',
      form: Object.assign({}, defaultForm)
    }
  },
  computed: {
    isEdit() {
      return this.$route.meta.isEdit
    },
    id() {
      return this.$route.params.id
    }
  },
  created() {
    if(this.isEdit) {
      this.getCategoryById()
    }
  },
  methods: {
    // 根据id获取商品类别
    async getCategoryById() {
      const result = await categoryApi.getCategoryById(this.id)
      this.form = result.data
    },
    // 添加或者编辑商品类别
    async onSubmit() {
      if(this.isEdit) {
        const result = await categoryApi.updateCategoryById(this.id, this.form)
        if(result.code===0) {
          this.$message.success('编辑成功')
        }else {
          this.$message.warning('编辑失败')
        }
      }else {
        const result = await categoryApi.addCategory(this.form)
        if(result.code===0) {
          this.$message.success('添加成功')
        }else {
          this.$message.warning('添加失败')
        }
      }
      this.goBack()
      this.reload()
    },
    goBack() {
      this.$router.go(-1)
    }
  },
  inject: ['reload']
}
</script>
<style lang="less" scoped>
  .category {
    margin: 100px;
    .el-input {
      width: 300px;
    }
  }
</style>
